package vector

import (
	"fmt"
	"log"
	"sync"

	"mcp-server/internal/types"
	"mcp-server/internal/vector/models"
	"mcp-server/internal/vector/processor"
)

// VectorService 向量化服务接口
type VectorService interface {
	// 初始化服务
	Initialize(config *ServiceConfig) error
	// 关闭服务
	Close() error

	// 向量化操作
	VectorizeText(text string, metadata map[string]interface{}) (*processor.VectorizeResult, error)
	VectorizeChunk(chunk *types.TextChunk) (*processor.VectorizeResult, error)
	VectorizeChunks(chunks []*types.TextChunk) (*processor.BatchVectorizeResult, error)
	VectorizeDocument(splitResult *types.SplitResult) (*processor.BatchVectorizeResult, error)

	// 质量控制
	ValidateConsistency(text string, attempts int) (*processor.ConsistencyResult, error)

	// 服务状态
	GetServiceStatus() map[string]interface{}
	GetModelInfo() *models.ModelInfo
	IsReady() bool
}

// ServiceConfig 服务配置
type ServiceConfig struct {
	ModelConfig      *models.ModelConfig         `json:"model_config"`
	VectorizerConfig *processor.VectorizerConfig `json:"vectorizer_config"`
	EnableMetrics    bool                        `json:"enable_metrics"`
	MetricsInterval  int                         `json:"metrics_interval"`
}

// DefaultServiceConfig 创建默认服务配置
func DefaultServiceConfig() *ServiceConfig {
	return &ServiceConfig{
		ModelConfig:      models.DefaultModelConfig(),
		VectorizerConfig: processor.DefaultVectorizerConfig(),
		EnableMetrics:    true,
		MetricsInterval:  60, // 60秒
	}
}

// VectorServiceImpl 向量化服务实现
type VectorServiceImpl struct {
	config     *ServiceConfig
	model      models.EmbeddingModel
	vectorizer *processor.Vectorizer
	metrics    *ServiceMetrics
	mutex      sync.RWMutex
	ready      bool
}

// ServiceMetrics 服务指标
type ServiceMetrics struct {
	TotalRequests    int64   `json:"total_requests"`
	SuccessRequests  int64   `json:"success_requests"`
	FailureRequests  int64   `json:"failure_requests"`
	AverageLatency   float64 `json:"average_latency_ms"`
	TotalProcessTime int64   `json:"total_process_time_ms"`
	mutex            sync.RWMutex
}

// NewVectorService 创建向量化服务
func NewVectorService() VectorService {
	return &VectorServiceImpl{
		config:  DefaultServiceConfig(),
		metrics: &ServiceMetrics{},
	}
}

// Initialize 初始化服务
func (vs *VectorServiceImpl) Initialize(config *ServiceConfig) error {
	vs.mutex.Lock()
	defer vs.mutex.Unlock()

	if config != nil {
		vs.config = config
	}

	log.Println("正在初始化向量化服务...")

	// 初始化嵌入模型
	vs.model = models.NewChineseEmbeddingModel()
	if err := vs.model.Initialize(vs.config.ModelConfig); err != nil {
		return fmt.Errorf("初始化嵌入模型失败: %v", err)
	}

	// 初始化向量化处理器
	vs.vectorizer = processor.NewVectorizer(vs.model)
	if err := vs.vectorizer.Initialize(vs.config.VectorizerConfig); err != nil {
		return fmt.Errorf("初始化向量化处理器失败: %v", err)
	}

	vs.ready = true
	log.Println("向量化服务初始化完成")

	return nil
}

// Close 关闭服务
func (vs *VectorServiceImpl) Close() error {
	vs.mutex.Lock()
	defer vs.mutex.Unlock()

	if !vs.ready {
		return nil
	}

	log.Println("正在关闭向量化服务...")

	// 关闭嵌入模型
	if vs.model != nil {
		if err := vs.model.Close(); err != nil {
			log.Printf("关闭嵌入模型时出错: %v", err)
		}
	}

	vs.ready = false
	log.Println("向量化服务已关闭")

	return nil
}

// VectorizeText 向量化文本
func (vs *VectorServiceImpl) VectorizeText(text string, metadata map[string]interface{}) (*processor.VectorizeResult, error) {
	if !vs.IsReady() {
		return nil, fmt.Errorf("向量化服务未就绪")
	}

	vs.updateMetrics(func() {
		vs.metrics.TotalRequests++
	})

	result, err := vs.vectorizer.VectorizeText(text, metadata)

	vs.updateMetrics(func() {
		if err != nil || !result.Success {
			vs.metrics.FailureRequests++
		} else {
			vs.metrics.SuccessRequests++
		}

		if result != nil {
			vs.metrics.TotalProcessTime += result.ProcessTime
			vs.metrics.AverageLatency = float64(vs.metrics.TotalProcessTime) / float64(vs.metrics.TotalRequests)
		}
	})

	return result, err
}

// VectorizeChunk 向量化文档分片
func (vs *VectorServiceImpl) VectorizeChunk(chunk *types.TextChunk) (*processor.VectorizeResult, error) {
	if !vs.IsReady() {
		return nil, fmt.Errorf("向量化服务未就绪")
	}

	return vs.vectorizer.VectorizeChunk(chunk)
}

// VectorizeChunks 批量向量化文档分片
func (vs *VectorServiceImpl) VectorizeChunks(chunks []*types.TextChunk) (*processor.BatchVectorizeResult, error) {
	if !vs.IsReady() {
		return nil, fmt.Errorf("向量化服务未就绪")
	}

	vs.updateMetrics(func() {
		vs.metrics.TotalRequests += int64(len(chunks))
	})

	result, err := vs.vectorizer.VectorizeChunks(chunks)

	if result != nil {
		vs.updateMetrics(func() {
			vs.metrics.SuccessRequests += int64(result.SuccessCount)
			vs.metrics.FailureRequests += int64(result.FailureCount)
			vs.metrics.TotalProcessTime += result.ProcessTime
			vs.metrics.AverageLatency = float64(vs.metrics.TotalProcessTime) / float64(vs.metrics.TotalRequests)
		})
	}

	return result, err
}

// VectorizeDocument 向量化整个文档
func (vs *VectorServiceImpl) VectorizeDocument(splitResult *types.SplitResult) (*processor.BatchVectorizeResult, error) {
	if !vs.IsReady() {
		return nil, fmt.Errorf("向量化服务未就绪")
	}

	return vs.vectorizer.VectorizeDocument(splitResult)
}

// ValidateConsistency 验证一致性
func (vs *VectorServiceImpl) ValidateConsistency(text string, attempts int) (*processor.ConsistencyResult, error) {
	if !vs.IsReady() {
		return nil, fmt.Errorf("向量化服务未就绪")
	}

	return vs.vectorizer.ValidateConsistency(text, attempts)
}

// GetServiceStatus 获取服务状态
func (vs *VectorServiceImpl) GetServiceStatus() map[string]interface{} {
	vs.mutex.RLock()
	defer vs.mutex.RUnlock()

	status := make(map[string]interface{})
	status["ready"] = vs.ready
	status["model_info"] = vs.GetModelInfo()

	if vs.config != nil {
		status["config"] = vs.config
	}

	if vs.metrics != nil {
		vs.metrics.mutex.RLock()
		status["metrics"] = map[string]interface{}{
			"total_requests":     vs.metrics.TotalRequests,
			"success_requests":   vs.metrics.SuccessRequests,
			"failure_requests":   vs.metrics.FailureRequests,
			"average_latency_ms": vs.metrics.AverageLatency,
			"success_rate":       vs.calculateSuccessRate(),
		}
		vs.metrics.mutex.RUnlock()
	}

	return status
}

// GetModelInfo 获取模型信息
func (vs *VectorServiceImpl) GetModelInfo() *models.ModelInfo {
	if vs.model != nil {
		return vs.model.GetModelInfo()
	}
	return nil
}

// IsReady 检查服务是否就绪
func (vs *VectorServiceImpl) IsReady() bool {
	vs.mutex.RLock()
	defer vs.mutex.RUnlock()

	return vs.ready && vs.model != nil && vs.vectorizer != nil && vs.vectorizer.IsInitialized()
}

// updateMetrics 更新指标
func (vs *VectorServiceImpl) updateMetrics(updateFunc func()) {
	if vs.metrics != nil {
		vs.metrics.mutex.Lock()
		updateFunc()
		vs.metrics.mutex.Unlock()
	}
}

// calculateSuccessRate 计算成功率
func (vs *VectorServiceImpl) calculateSuccessRate() float64 {
	if vs.metrics.TotalRequests == 0 {
		return 0.0
	}
	return float64(vs.metrics.SuccessRequests) / float64(vs.metrics.TotalRequests)
}

// SetConfig 设置配置
func (vs *VectorServiceImpl) SetConfig(config *ServiceConfig) {
	vs.mutex.Lock()
	defer vs.mutex.Unlock()

	if config != nil {
		vs.config = config
	}
}

// GetConfig 获取配置
func (vs *VectorServiceImpl) GetConfig() *ServiceConfig {
	vs.mutex.RLock()
	defer vs.mutex.RUnlock()

	return vs.config
}

// ResetMetrics 重置指标
func (vs *VectorServiceImpl) ResetMetrics() {
	if vs.metrics != nil {
		vs.metrics.mutex.Lock()
		vs.metrics.TotalRequests = 0
		vs.metrics.SuccessRequests = 0
		vs.metrics.FailureRequests = 0
		vs.metrics.AverageLatency = 0
		vs.metrics.TotalProcessTime = 0
		vs.metrics.mutex.Unlock()
	}
}
